﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ciripescu_WebRole.BL;
using Ciripescu_WebRole.Entities;


namespace Ciripescu_WebRole
{
    public partial class WriteCirip : System.Web.UI.UserControl
    {

        public delegate void ScrieEventHandler(object sender, EventArgs e);

        public event ScrieEventHandler Scrie;

        public string InReplyToUser
        {
            get 
            {
                if (Request.QueryString["InReplyToUser"] != null)
                    return Request.QueryString["InReplyToUser"];
                else
                    return (string)ViewState["InReplyToUser"]; 
            }
            set
            {
                if (string.IsNullOrEmpty(value))
                {
                    ViewState.Remove("InReplyToUser");
                    // daca valoarea nu vine din viewstate ci din querystring singurul mod in care se poate
                    // scapa de ea e redirectand
                    if (Request.QueryString["InReplyToUser"] != null)
                        Response.Redirect(Request.CurrentExecutionFilePath);
                }
                else ViewState["InReplyToUser"] = value;
            }
        }
        
        public string InReplyToId
        {
            get 
            {
                if (Request.QueryString["InReplyToId"] != null)
                    return Request.QueryString["InReplyToId"];
                else
                    return (string)ViewState["InReplyToId"]; 
            }
            set
            {
                if (string.IsNullOrEmpty(value))
                {
                    // daca valoarea nu vine din viewstate ci din querystring singurul mod in care se poate
                    // scapa de ea e redirectand
                    ViewState.Remove("InReplyToId");
                    if (Request.QueryString["InReplyToId"] != null)
                        Response.Redirect(Request.CurrentExecutionFilePath);
                }
                else ViewState["InReplyToId"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            
        }

        // copiata din displayCirips.ascx.cs
        public string RaspunsLa(string InReplyToUser)
        {
            if (string.IsNullOrEmpty(InReplyToUser))
                return string.Empty;

            //return "@<a href='/profile.aspx?userName=" + InReplyToUser + "' class='mylink'>" + InReplyToUser + "</a>: ";
            return "@<a href='/u/" + InReplyToUser + "/' class='mylink'>" + InReplyToUser + "</a>: ";
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            CiripManager cm = new CiripManager();
            Cirip last = cm.GetFirst((string)Session["UserName"]);
            if (last != null)
                lblLatest.Text = RaspunsLa(last.InReplyToUser)+last.Content;
            else 
                lblTextLatest.Visible = false;
            UpdateDisplay();
        }
        
        public void UpdateDisplay()
        {
            if (string.IsNullOrEmpty(InReplyToUser))
            {
                lblTitlu.Text = "...zic si eu";
                btnCancel.Visible = false;
            }
            else
            {
                lblTitlu.Text = "Raspunde lui " + InReplyToUser;
                btnCancel.Visible = true;
            }
        }
        
        protected void btnSendCirip_Click(object sender, EventArgs e)
        {
            if (txtCirip.Text.Length > 255)
            {
                errors.InnerHtml = "Textul introdus este prea lung (mai mare de 255 caractere).<br>";
                return;
            }
            if (txtCirip.Text == String.Empty)
            {
                errors.InnerHtml = "Trebuie sa scrii ceva in casuta de mai jos.<br>";
                return;
            }
            CiripManager cm = new CiripManager();
            CiripCacheManager cache = new CiripCacheManager();

            Cirip c = new Cirip((string)Session["UserName"], txtCirip.Text);

            // To future me: chiar imi pare rau pt codul asta. iarta-ma!
            if (!string.IsNullOrEmpty(InReplyToUser))
            {               

                // Daca este un reply pune-l intr-o tabela separata cu destinatarul ca PartitionKey sa se poata accesa repede,
                // dar lasa o copie si in tabela Cirip ca sa putem extrage reply-urile impreuna cu Ciripurile normale
                // fara inca o interogare in plus
                CiripMessageManager msgManager = new CiripMessageManager();
                CiripMessage msg = new CiripMessage((string)Session["UserName"], this.InReplyToUser, txtCirip.Text, 1, this.InReplyToId);
                msg.RowKey = c.RowKey; // cloneaza RowKey-ul ca sa fie la fel mesajele
                msgManager.Insert(msg);

                c.InReplyToUser = this.InReplyToUser;
                c.InReplyToId = this.InReplyToId;
                cm.Insert(c);
                cache.Insert(new CiripCache(c));

                // am facut insertul inainte sa curat aceste valori pt ca daca ele is in querystring
                // se va face redirect si nimic dupa ele nu se mai executa!!!!!
                this.InReplyToId = string.Empty;
                this.InReplyToUser = string.Empty;
            }
            else
            {
                cm.Insert(c);
                cache.Insert(new CiripCache(c));
            }

            // salvam data cand s-a scris ultimul cirip pt ca vom putea zice in sitemap la spideri
            // sa nu mai descarce o pagina daca au deja ultima versiune
            UserManager um = new UserManager();
            User user = um.GetItem((string)Session["UserName"]);
            user.LastCirip = DateTime.Now;
            um.Save(user);

            txtCirip.Text = string.Empty;
            UpdateDisplay();

            //raise the event scrie, doar pentru pagina de home.
            
            if(Request.Url.ToString().Contains("home"))
            Scrie(this, e);
        }

        protected void btnCancel_Click(object sender, ImageClickEventArgs e)
        {
            InReplyToUser = string.Empty;
            InReplyToId   = string.Empty;
            txtCirip.Text = String.Empty;
            UpdateDisplay();
        }
    }
}